package com.api.shopapi.controller;

import com.alibaba.fastjson.JSONObject;
import com.api.shopapi.entity.*;
import com.api.shopapi.entity.dto.RoomTypeDTO;
import com.api.shopapi.entity.dto.UserFaceDTO;
import com.api.shopapi.service.*;
import com.api.shopapi.util.Util;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;


@RestController
@RequestMapping("UserFace")
public class UserFaceController extends BaseController{

    @Autowired
    @Qualifier("UserFaceServiceImplOne")
    private UserFaceService userFaceService;


    @Autowired
    @Qualifier("UserServiceImplOne")
    private UserService userService;


    @Autowired
    @Qualifier("ElderlyServiceImplOne")
    private ElderlyService elderlyService;


    @Autowired
    @Qualifier("MedicinerServiceImplOne")
    private MedicinerService medicinerService;


    @Autowired
    @Qualifier("NurseServiceImplOne")
    private NurseService nurseService;


    @Autowired
    @Qualifier("NurseAideServiceImplOne")
    private NurseAideService nurseAideService;


    @Autowired
    @Qualifier("InstitutionServiceImplOne")
    private InstitutionService institutionService;


    @Autowired
    @Qualifier("InstitutionStaffRelServiceImplOne")
    private InstitutionStaffRelService institutionStaffRelService;


    @Autowired
    @Qualifier("StaffServiceImplOne")
    private StaffService staffService;



    @RequestMapping(value = "AddImg",method = RequestMethod.POST)
    public MyResult AddImg(@RequestBody JSONObject jsonObject){
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");

            String elderlyCode = jsonObject.getString("elderlyCode");

            String faceImg = jsonObject.getString("faceImg");


            PreCheck preCheck=checkSignFrontInterface(timeStr,sign,"/ElderlyFace/AddImg");
            if(preCheck.getError()==1){
                return failed(preCheck.getMessage());
            }

            byte[] imgByte = base64String2ByteFun(faceImg);



            File file1 = new File(imgsRootPath);
            if (!file1.exists()) {//如果文件夹不存在
                file1.mkdir();//创建文件夹
            }

            File file2 = new File(rootPath);
            if (!file2.exists()) {//如果文件夹不存在
                file2.mkdir();//创建文件夹
            }


            String fdPath = imgsRootPath+"\\"+elderlyCode;
            File fd =new File(fdPath);
            if(!fd.exists()){
                fd.mkdir();
            }

            String filePath = fdPath + "\\" +  getTimeStr() + ".jpg";
            //File file =new File(filePath);


            //BASE64Decoder decoder = new BASE64Decoder();
            //byte[] imgbyte = decoder.decodeBuffer("刚刚将字节数组转成的字符串");

            OutputStream os = new FileOutputStream(filePath);
            os.write(imgByte, 0, imgByte.length);
            os.flush();
            os.close();


            JSONObject jsonObject1 =new JSONObject();
            return success(jsonObject1);
        } catch (Exception e) {
            insertError("/ElderlyFace/AddImg",jsonObject.toJSONString(),getExceptionMsg(e),"api");
            return anomalous(getExceptionMsg(e));
        }
    }


    //人脸注册
    @RequestMapping(value = "Add",method = RequestMethod.POST)
    public MyResult Add(@RequestBody JSONObject jsonObject){
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");

            String userCode = jsonObject.getString("userCode");
            String faceImg = jsonObject.getString("faceImg");
            String faceFeature = jsonObject.getString("faceFeature");

            PreCheck preCheck=checkSignFrontInterface(timeStr,sign,"/UserFace/Add");
            if(preCheck.getError()==1){
                return failed(preCheck.getMessage());
            }

            User user = userService.getByUserCode(userCode);



            UserFace userFace = userFaceService.getByUserCode(userCode);
            if(userFace != null){
                return failed("人脸已注册");
            }

            userFace = new UserFace();
            userFace.setUserFaceCode(UUID.randomUUID().toString());
            userFace.setUserCode(userCode);
            userFace.setUserName(user.getName());
            userFace.setFaceImg(base64String2ByteFun(faceImg));
            userFace.setFaceFeature(base64String2ByteFun(faceFeature));
            userFace.setGovernmentCode(user.getGovernmentCode());
            userFace.setInstitutionCode(user.getInstitutionCode());
            userFaceService.insert(userFace);


            JSONObject jsonObject1 =new JSONObject();
            return success(jsonObject1);
        } catch (Exception e) {
            //insertError("/ElderlyFace/Add",jsonObject.toJSONString(),getExceptionMsg(e),"api");
            return anomalous(getExceptionMsg(e));
        }
    }

    //人脸编辑
    @RequestMapping(value = "Edit",method = RequestMethod.POST)
    public MyResult Edit(@RequestBody JSONObject jsonObject){
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");

            String userFaceCode = jsonObject.getString("userFaceCode");
            String faceImg = jsonObject.getString("faceImg");
            String faceFeature = jsonObject.getString("faceFeature");

            PreCheck preCheck=checkSignFrontInterface(timeStr,sign,"/UserFace/Edit");
            if(preCheck.getError()==1){
                return failed(preCheck.getMessage());
            }


            UserFace userFace = userFaceService.getByUserFaceCode(userFaceCode);
            if(userFace == null){
                return failed("人脸未注册");
            }

            userFace.setFaceImg(base64String2ByteFun(faceImg));
            userFace.setFaceFeature(base64String2ByteFun(faceFeature));
            userFaceService.update(userFace);

            JSONObject jsonObject1 =new JSONObject();
            return success(jsonObject1);
        } catch (Exception e) {
            //insertError("/ElderlyFace/Add",jsonObject.toJSONString(),getExceptionMsg(e),"api");
            return anomalous(getExceptionMsg(e));
        }
    }


    //获取人脸信息
    @RequestMapping(value = "Get",method = RequestMethod.POST)
    public MyResult Get(@RequestBody JSONObject jsonObject){
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");

            String userFaceCode = jsonObject.getString("userFaceCode");

            PreCheck preCheck=checkSignFrontInterface(timeStr,sign,"/UserFace/Get");
            if(preCheck.getError()==1) {
                return failed(preCheck.getMessage());
            }

            UserFace userFace = userFaceService.getByUserFaceCode(userFaceCode);

            UserFaceDTO userFaceDTO = mapper.map(userFace, UserFaceDTO.class);
            userFaceDTO.setFaceImgStr(byte2Base64StringFun(userFace.getFaceImg()));
            userFaceDTO.setFaceFeatureStr(byte2Base64StringFun(userFace.getFaceFeature()));

            userFaceDTO.setFaceImg(null);
            userFaceDTO.setFaceFeature(null);

            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("userFace",userFaceDTO);

            return success(jsonObject1);
        } catch (Exception e) {
            insertError("/UserFace/Get",jsonObject.toJSONString(),getExceptionMsg(e),"api");
            return anomalous(getExceptionMsg(e));
        }
    }

    //获取人脸信息
    @RequestMapping(value = "GetByUserCode",method = RequestMethod.POST)
    public MyResult GetByUserCode(@RequestBody JSONObject jsonObject){
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");

            String userCode = jsonObject.getString("userCode");

            PreCheck preCheck=checkSignFrontInterface(timeStr,sign,"/UserFace/GetByUserCode");
            if(preCheck.getError()==1) {
                return failed(preCheck.getMessage());
            }

            UserFace userFace = userFaceService.getByUserCode(userCode);
            if(userFace == null){
                return failed("人脸未注册");
            }

            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("userFace",userFace);

            return success(jsonObject1);
        } catch (Exception e) {
            insertError("/UserFace/GetByUserCode",jsonObject.toJSONString(),getExceptionMsg(e),"api");
            return anomalous(getExceptionMsg(e));
        }
    }


    //ins
    @RequestMapping(value = "InsPage", method = RequestMethod.POST)
    public MyResult InsPage(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");

            int userType = jsonObject.getInteger("userType");
            String userName = jsonObject.getString("userName");

            int pageIndex = jsonObject.getInteger("pageIndex");
            int pageSize = jsonObject.getInteger("pageSize");

            PreCheck preCheck = checkSignAdmInterface(timeStr,sign,staffCode,"/UserFace/InsPage");
            if(preCheck.getError() == 1){
                return failed(preCheck.getMessage());
            }

            InstitutionStaffRel institutionStaffRel = institutionStaffRelService.getByStaffCode(staffCode);
            String institutionCode = institutionStaffRel.getInstitutionCode();

            PageInfo<UserFace> pageInfo = userFaceService.pageByInsCode(pageIndex, pageSize, institutionCode,
                    userName,userType);
            List<UserFaceDTO> listDTO = new ArrayList<>();
            for(UserFace userFace:pageInfo.getList()){
                UserFaceDTO userFaceDTO = mapper.map(userFace,UserFaceDTO.class);

                User user = userService.getByUserCode(userFace.getUserCode());
                if(user.getUserType() == 1){
                    Elderly elderly = elderlyService.getByUserCode(user.getUserCode());
                    userFaceDTO.setIdCard(elderly.getIdCard());
                }
                if(user.getUserType() == 7){
                    Mediciner mediciner = medicinerService.getByUserCode(user.getUserCode());
                    userFaceDTO.setIdCard(mediciner.getIdCard());
                }
                if(user.getUserType() == 8){
                    Nurse nurse = nurseService.getByUserCode(user.getUserCode());
                    userFaceDTO.setIdCard(nurse.getIdCard());
                }
                if(user.getUserType() == 9){
                    NurseAide nurseAide = nurseAideService.getByUserCode(user.getUserCode());
                    userFaceDTO.setIdCard(nurseAide.getIdCard());
                }

                listDTO.add(userFaceDTO);
            }
            pageInfo.setList(Collections.unmodifiableList(listDTO));


            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("pageInfo",pageInfo);

            return success(jsonObject1);
        }catch (Exception e){
            insertError("/UserFace/InsPage", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }

    }

    //gov
    @RequestMapping(value = "GovPage", method = RequestMethod.POST)
    public MyResult GovPage(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");

            int userType = jsonObject.getInteger("userType");
            String userName = jsonObject.getString("userName");

            int pageIndex = jsonObject.getInteger("pageIndex");
            int pageSize = jsonObject.getInteger("pageSize");

            PreCheck preCheck = checkSignAdmInterface(timeStr,sign,staffCode,"/UserFace/GovPage");
            if(preCheck.getError() == 1){
                return failed(preCheck.getMessage());
            }

            Staff staff = staffService.getByStaffCode(staffCode);

            PageInfo<UserFace> pageInfo = userFaceService.pageByGovCode(pageIndex, pageSize, staff.getGovernmentCode(),
                    userName,userType);
            List<UserFaceDTO> listDTO = new ArrayList<>();
            for(UserFace userFace:pageInfo.getList()){
                UserFaceDTO userFaceDTO = mapper.map(userFace,UserFaceDTO.class);

                User user = userService.getByUserCode(userFace.getUserCode());
                if(user.getUserType() == 1){
                    Elderly elderly = elderlyService.getByUserCode(user.getUserCode());
                    userFaceDTO.setIdCard(elderly.getIdCard());
                }
                if(user.getUserType() == 7){
                    Mediciner mediciner = medicinerService.getByUserCode(user.getUserCode());
                    userFaceDTO.setIdCard(mediciner.getIdCard());
                }
                if(user.getUserType() == 8){
                    Nurse nurse = nurseService.getByUserCode(user.getUserCode());
                    userFaceDTO.setIdCard(nurse.getIdCard());
                }
                if(user.getUserType() == 9){
                    NurseAide nurseAide = nurseAideService.getByUserCode(user.getUserCode());
                    userFaceDTO.setIdCard(nurseAide.getIdCard());
                }

                listDTO.add(userFaceDTO);
            }
            pageInfo.setList(Collections.unmodifiableList(listDTO));


            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("pageInfo",pageInfo);

            return success(jsonObject1);

        }catch (Exception e){
            insertError("/UserFace/GovPage", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }

    }


    //人脸列表
    @RequestMapping(value = "InsPageApp", method = RequestMethod.POST)
    public MyResult InsPageApp(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String userCode = jsonObject.getString("userCode");

            int userType = jsonObject.getInteger("userType");
            String userName = jsonObject.getString("userName");

            int pageIndex = jsonObject.getInteger("pageIndex");
            int pageSize = jsonObject.getInteger("pageSize");

            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/UserFace/InsPageApp");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            Institution institution = institutionService.getByUserCode(userCode);
            String insCode = institution.getInstitutionCode();

            PageInfo<UserFace> pageInfo = userFaceService.pageByInsCode(pageIndex, pageSize, insCode,
                    userName,userType);
            List<UserFaceDTO> listDTO = new ArrayList<>();
            for(UserFace userFace:pageInfo.getList()){
                UserFaceDTO userFaceDTO = mapper.map(userFace,UserFaceDTO.class);

                User user = userService.getByUserCode(userFace.getUserCode());
                if(user.getUserType() == 1){
                    Elderly elderly = elderlyService.getByUserCode(user.getUserCode());
                    userFaceDTO.setIdCard(elderly.getIdCard());
                }
                if(user.getUserType() == 7){
                    Mediciner mediciner = medicinerService.getByUserCode(user.getUserCode());
                    userFaceDTO.setIdCard(mediciner.getIdCard());
                }
                if(user.getUserType() == 8){
                    Nurse nurse = nurseService.getByUserCode(user.getUserCode());
                    userFaceDTO.setIdCard(nurse.getIdCard());
                }
                if(user.getUserType() == 9){
                    NurseAide nurseAide = nurseAideService.getByUserCode(user.getUserCode());
                    userFaceDTO.setIdCard(nurseAide.getIdCard());
                }

                listDTO.add(userFaceDTO);
            }
            pageInfo.setList(Collections.unmodifiableList(listDTO));


            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("pageInfo",pageInfo);

            return success(jsonObject1);
        } catch (Exception e) {
            insertError("/UserFace/InsPageApp", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }




}
